package com.mmall.concurrency.example.aqs;

import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.mmall.concurrency.example.atomic.AtomicExample3;

// 给定执行时间，在指定时间没有执行完，也不等待了，继续执行await后面的代码！但是那些线程并不会终止，会继续执行完毕。
@Slf4j
public class CountDownLatchExample2 {
	private static Logger log = LoggerFactory.getLogger(AtomicExample3.class);

    private static int threadCount = 200;

    public static void main(String[] args) throws Exception{
        ExecutorService executorService = Executors.newCachedThreadPool();

        final CountDownLatch countDownLatch = new CountDownLatch(threadCount);

        for (int i = 0; i < threadCount; i++) {
            final int threadNumber = i;
//            Thread.sleep(1); // 这里sleep()根本没有用
            executorService.execute(()->{
                try{
                    test(threadNumber);
                }catch (Exception e){
                    log.error("exception", e);
                }finally {
                    countDownLatch.countDown(); // 还可以放在你自己的条件中
                }
            });
        }
        countDownLatch.await(10, TimeUnit.MILLISECONDS); // 这里统计的时间是test方法执行的时间
        log.info("finish");
        executorService.shutdown(); // 如果线程池不再使用，不要忘记关闭, 并不会及时关闭，会等上面的线程全部执行完，才会关闭
    }

    private static void test(int threadNumber) throws Exception{
        Thread.sleep(100);
        log.info("{}", threadNumber);
    }
}
